{% extends 'layout/manage.html' %} 
{% load static %} 
{% block css %}
<link
  rel="stylesheet"
  href="{% static 'plugin/editor-md/css/editormd.min.css' %}"
/>
<style>
  .panel-default {
    margin-top: 10px;
  }

  .panel-default .panel-heading {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }

  .panel-body {
    padding: 0;
  }

  .title-list {
    border-right: 1px solid #dddddd;
    min-height: 500px;
  }

  .title-list ul {
    padding-left: 15px;
  }

  .title-list ul a {
    display: block;
    padding: 5px 0;
  }

  .content {
    border-left: 1px solid #dddddd;
    min-height: 600px;
    margin-left: -1px;
  }
  .editormd-fullscreen {
    z-index: 1001;
  }
</style>
{% endblock %} 
{% block content %}
<div class="container-fluid">
  <div class="panel panel-default">
    <div class="panel-heading">
      <div><i class="fa fa-book" aria-hidden="true"></i>产量</div>
    </div>
    <div class="panel-body">
    
     <h2>output</h2>
      
    </div>
  </div>
</div>
{% endblock %} 
{% block js %}
<script src="{% static 'plugin/editor-md/editormd.min.js' %}"></script>
<script>
  // 在打开弹窗时添加同源策略参数
  // const popup = window.open('about:blank', '_blank', 'same-origin');
  // popup.document.write('<html>...</html>'); // 直接操作新窗口DOM
  // http://127.0.0.1:8000/manage/4/wiki/detail/
  var WIKI_DETAIL_URL = "{% url 'wiki' project_id=request.tracer.project.id %}";
  var WIKI_UPLOAD_URL =  "{% url 'wiki_upload_img' project_id=request.tracer.project.id %}";
  $(function () {
  });
  function initEditorMd() {
    editormd("editor", {
      placeholder: "##问题描述：#发生频次，#是否存在机种，物料，载具，版本，硬件，账号等相关性因素影响：#如何恢复：#根本原因：#解决措施：##",
      height: 500,
      path: "{% static 'plugin/editor-md/lib/' %}", //此处不能用反斜杠plugin\editor-md\lib\，要用正斜杠plugin/editor-md/lib/
      imageUpload:true,
      emoji: true,
      imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
      imageUploadURL:WIKI_UPLOAD_URL,
      //自定义图片上传逻辑
      onImageUpload: function(files, thisEditor) {
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        iframe.sandbox='allow-scripts allow-same-origin';// 安全沙箱策略
        document.body.appendChild(iframe);
        const form = iframe.contentDocument.createElement('form');
        form.method = 'POST';
        form.action = WIKI_UPLOAD_URL;
        form.enctype = 'multipart/form-data';

        const input = iframe.contentDocument.createElement('input');
        input.type = 'file';
        input.name = 'editormd-image-file';
        input.files = files;
      
        form.appendChild(input);
        iframe.contentDocument.body.appendChild(form);
        form.submit();
        // 监听iframe加载完成
        iframe.onload = function() {
          try {
            const response = JSON.parse(iframe.contentDocument.body.textContent);
            if (response.success) {
              this.insertValue(`![${files[0].name}](${response.url})`);
            }
          } catch(e) {
            console.error('解析响应失败:', e);
          }
          document.body.removeChild(iframe);
        };
        console.log("Uploading images:", files);
        var formData = new FormData();
        formData.append('editormd-image-file', files[0]);
        $.ajax({
          url: WIKI_UPLOAD_URL,
          type: 'POST',
          data: formData,
          processData: false,
          contentType: false,
          success: function(response) {
            console.log("Upload success:", response);
            if (response.success === 1) {
              thisEditor.insertValue(`![${files[0].name}](${response.url})`);
            } else {
              alert("图片上传失败: " + response.message);
            }
          },
          error: function(xhr, status, error) {
            console.error("Upload error:", xhr.responseText);
            alert("图片上传失败: " + xhr.responseText);
          }
        });
        return false; // 阻止默认上传行为
      }

    
    });
  }

  function initCatalog() {
    $.ajax({
      url: "{% url 'wiki_catalog' project_id=request.tracer.project.id %}",
      type: "GET",
      dataType: "json",
      success: function (res) {
        if (res.status) {
          $.each(res.data, function (index, item) {
            var href = WIKI_DETAIL_URL + "?wiki_id=" + item.id;
            var li = $("<li>")
              .attr("id", "id_" + item.id)
              .append($("<a>").text(item.title).attr("href", href))
              .append($("<ul>"));
            if (!item.parent_id) {
              //<li><a href="#">目录1</a></li>
              //添加到catalog中
              $("#catalog").append(li);
            } else {
              $("#id_" + item.parent_id)
                .children("ul")
                .append(li);
            }
          });
        } else {
          alert("获取目录失败");
        }
      },
    });
  }
</script>
{% endblock %}
